const mongoose = require('mongoose');
const { User } = require('./db/user');

async function initUsers() {
  try {
    console.log('初始化用户数据...\n');
    
    // 连接数据库
    await mongoose.connect('mongodb+srv://2334231668:xin123666@cluster0.13va5ah.mongodb.net/2410B');
    console.log('✅ 数据库连接成功');
    
    // 检查是否已有用户
    const existingUsers = await User.find({});
    console.log(`现有用户数量: ${existingUsers.length}`);
    
    if (existingUsers.length === 0) {
      console.log('创建默认用户...');
      
      // 创建admin用户
      const adminUser = new User({
        _id: new mongoose.Types.ObjectId('68aeed055e85b6f7f7ff0480'),
        username: 'admin',
        password: '123',
        avatar: 'https://picsum.photos/80',
        createdAt: new Date()
      });
      
      await adminUser.save();
      console.log('✅ admin用户创建成功');
      
      // 创建测试用户
      const testUser = new User({
        username: 'testuser',
        password: '123456',
        avatar: 'https://picsum.photos/80',
        createdAt: new Date()
      });
      
      await testUser.save();
      console.log('✅ testuser用户创建成功');
      
    } else {
      console.log('用户已存在，跳过创建');
      existingUsers.forEach((user, index) => {
        console.log(`${index + 1}. ${user.username} (${user._id})`);
      });
    }
    
    // 验证用户
    const allUsers = await User.find({});
    console.log(`\n总用户数: ${allUsers.length}`);
    
  } catch (error) {
    console.error('❌ 初始化失败:', error.message);
  } finally {
    await mongoose.disconnect();
    console.log('\n数据库连接已关闭');
  }
}

// 运行初始化
initUsers();
